import './ToDoList.css'
import { useSelector, useDispatch } from 'react-redux';
import { add, deleteItem, finishToDo, toggle } from '../../store/modules/ToDoListStore';
import { useState, useRef } from 'react';


function ToDoList() {
    let { list } = useSelector(state => state.todolist)
    const dispatch = useDispatch()
    const [input, setInput] = useState('');
    function addTodo(e) {
        if (e.key == 'Enter' && e.target.value) {
            dispatch(add(input));
            // 输入回车后清空输入框（通过为input赋值空字符串实现）
            setInput('');
        }
    }
    function deleteToDo(id) {
        // console.log(itemRef.current.id);
        // if (itemRef.current.id) {
        //     dispatch(deleteItem(itemRef.current.id));
        // }
        dispatch(deleteItem(id));
    }
    function toggle_check(item) {
        dispatch(finishToDo({
            id: item.id,
            completed: item.completed
        }
        ))
    }
    function toggleAll() {
        dispatch(toggle())
    }

    return (
        <section className="todoapp">
            <header className="header">
                <h1>todos</h1>
                <input
                    className="new-todo"
                    autoFocus
                    autoComplete="off"
                    placeholder="What needs to be done?"
                    // ref={itemRef}
                    value={input}
                    onKeyUp={(e) => { addTodo(e) }}
                    onChange={(e) => { setInput(e.target.value) }}
                />
            </header>
            <section className="main">
                <input id="toggle-all" className="toggle-all" type="checkbox" />
                <label htmlFor="toggle-all" onClick={toggleAll}></label>
                <ul className="todo-list">
                    {list.map((item) => (
                        <li className={item.completed ? "todo completed" : "todo"} key={item.id}>
                            <div className="view">
                                <input className="toggle" type="checkbox" checked={item.completed} onChange={() => { toggle_check(item) }} />
                                <label>{item.title}</label>
                                <button className="destroy" onClick={() => deleteToDo(item.id)}></button>
                            </div>
                        </li>
                    ))}
                </ul>
            </section>
        </section>
    )
}

export default ToDoList;